package com.pkk.penguin.frame.know.java.Javacoreknowledge.thread;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: peikunkun
 * @create: 2020-01-20 10:07
 **/
public class ThreadPoolSingle {

  /**
   * 默认的核心线程大小
   */
  private static int DEFAULT_CORE_POOL_SIZE = 10;

  /**
   * 最大线程大小
   */
  private static int DEFAULT_MAX_POOL_SIZE = 10;

  /**
   * 默认存活时间
   */
  private static int DEFAULT_KEEP_ALIVE_TIME = 300;


  private static int corePoolSize;
  private static int maxPoolSize;
  private static int keepAliveTime;


  private static ThreadPoolExecutor poolExecutor = null;


  public static ThreadPoolExecutor instand(int corePoolSize, int maxPoolSize, int keepAliveTimeSecord) {
    return build(corePoolSize, maxPoolSize, keepAliveTimeSecord);
  }


  public static ThreadPoolExecutor instand() {
    return build(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAX_POOL_SIZE, DEFAULT_KEEP_ALIVE_TIME);
  }


  private static ThreadPoolExecutor build(int corePoolSize, int maxPoolSize, int keepAliveTime) {
    if (corePoolSize <= 0) {
      corePoolSize = DEFAULT_CORE_POOL_SIZE;
    }
    if (maxPoolSize <= 0) {
      maxPoolSize = DEFAULT_MAX_POOL_SIZE;
    }
    if (keepAliveTime <= 0) {
      keepAliveTime = DEFAULT_KEEP_ALIVE_TIME;
    }

    if (null == poolExecutor) {
      synchronized (ThreadPoolSingle.class) {
        if (null == poolExecutor) {
          poolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
              new LinkedTransferQueue(), Executors.defaultThreadFactory(), new DiscardPolicy());
        }
      }
    }
    return poolExecutor;
  }

  private ThreadPoolSingle() {
  }

}
